package com.botao.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.botao.cms.dao.LogMapper;
import com.botao.cms.pojo.Log;
import com.botao.cms.service.LogService;
import com.botao.cms.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Transactional(rollbackFor = Exception.class)
@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService {
    @Autowired
    LogMapper logMapper;

    @Override
    public void exportLog(HttpServletResponse response) throws IOException {
        List<Log> logList = logMapper.selectList(new QueryWrapper<Log>().orderByDesc("created"));

        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        response.setContentType("application/octet-stream;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + "log.log");
        logList.forEach(log -> {
            String time = DateUtil.format(log.getCreated());
            String user = log.getUser();
            String host = log.getHost();
            String action = log.getAction();
            String level = log.getLevel().toString();

            StringBuilder sb = new StringBuilder();
            sb.append("[")
                    .append(time)
                    .append("] 级别：")
                    .append(level)
                    .append(" 登录邮箱：")
                    .append(user)
                    .append(" 主机：")
                    .append(host)
                    .append(" 操作：")
                    .append(action)
                    .append("\n");
            try {
                bos.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        bos.flush();
        bos.close();
        os.flush();
        os.close();
    }
}
